﻿using SimpleESBCore.Implement;
using SimpleESBCore.Implement.Datas;
using SimpleESBCore.Implement.Events;
using SimpleESBCore.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SimpleESBCore.Common
{
    public class SendHelper
    {
        public void SendData(Socket socket, EventBase eventBase, ISerialization serialization)
        {
            if (socket.Connected)
            {
                string message = serialization.Serializer(eventBase);
                byte[] bufferData = Encoding.Unicode.GetBytes(message);
                //先发送数据配置信息
                DataSendEvent dataSendEvent = new DataSendEvent();
                dataSendEvent.EventData = new DataConfigData(bufferData.Length);
                string strConfig = serialization.Serializer<DataSendEvent>(dataSendEvent);
                byte[] bufferConfig = Encoding.Unicode.GetBytes(strConfig);

                socket.Send(bufferConfig);
                socket.Send(bufferData);
            }
            else
            {
                throw new Exception(string.Format("客户端{0}的连接已断开!", socket.AddressFamily.ToString()));
            }
        }
    }
}
